class UserToolSetting::WeatherForecast < UserToolSetting
  
  belongs_to :city
  belongs_to :area  
  
  def date_type
    ActiveSupport::StringInquirer.new(self[:date_type])
  end
  
  def send_email!(options = {})
    send_email_block! do
      UserMailer.deliver_send_weather_forecast self, options
    end    
  end
  
  def send_sm!(pri = 1)
    send_sm_block! do
      Sm.create!( :user => user,
          :content => sm_content,
          :pri => pri)
    end
  end
  
  def syn_send_sm!(args = { :by => 'maple20' })
    logger.debug sm_content
    send_sm_block! do
      if args[:by].to_s == 'lite'
        user.send_sm_by_lite_fetion sm_content
      else
        FetionSm.new( 
          :mobile => user.mobile,
          :password => user.fetion_password,
          :content => sm_content  ).create!
      end
    end
  end
  
  def sm_content 
     date_type.tomorrow? ? area.weather_forecast_sm : area.today_weather_sm
  end

  def self.send_emails
    email_settings = all(
      :conditions => [
        '        forecasted_hour = ?
          and (Date(emailed_at) < ?
            or (Date(emailed_at) = ? and Hour(emailed_at) < ? )
            or emailed_at is null)
          and allow_sms = ? ',
        Time.now.hour,
        Date.today,
        Date.today,
        Time.now.hour,
        'yes'
      ],
      :order => 'rand()'
    )
#    email_settings.in_groups_of(5,false).each_with_object([]) do |settings,threads|
#      threads << Thread.new(settings) do |settings|
#        settings.each do |setting|
##          puts "setting_#{setting.id} #{setting.tool.name} to #{setting.user.email}...#{setting.emailed_at.to_formatted_s(:db)}"
#          setting.send_email 
##          puts 'end'
#        end
#      end
#    end.each do |thread|
#      thread.join
#    end
    email_settings.each do |setting|
      setting.send_email 
    end
    SmsEmailsDailyStat.today_stat.add_emails_count!(:emails_count => email_settings.size )
  end

  def self.send_sms(pri = 1)
    all(
      :conditions => [
        '        forecasted_hour = ?
          and (Date(smed_at) < ?
            or (Date(smed_at) = ? and Hour(smed_at) < ? )
            or smed_at is null)
          and allow_sms = ? ',
        Time.now.hour,
        Date.today,
        Date.today,
        Time.now.hour,
        'yes'
      ]
    ).each do |setting|
      setting.send_sm(pri)
    end
      #in_groups_of(20,false).each_with_object([]) do |settings,threads|
      #threads << Thread.new(settings) do |settings|
      #  settings.each do |setting|
      #    puts "setting_#{setting.id} #{setting.tool.name} to #{setting.user.mobile}...#{setting.smed_at.to_formatted_s(:db)}"
          
      #    puts 'end'
      # end 
      # end
    #end.each do |thread|
    #  thread.join
    #end
  end
end
